<?php
/**
 * @author spenceryg
 * @date 2023/3/15
 * @time 6:21 下午
 * @focus love & life
 */


namespace app\api\controller;


use app\common\lib\Chat2;
use app\common\lib\ChatGpt;
use app\common\lib\Crontab;
use app\common\model\GptToken;
use app\common\model\PushPlan;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use thans\jwt\facade\JWTAuth;
use hg\apidoc\annotation as Apidoc;
use think\facade\View;


/**
 * @Apidoc\Title("Test")
 * Class Test
 * @package app\api\controller
 */
class Test extends \app\BaseController
{


    /**
     * tranOpenId
     * @Apidoc\Title("转换openid")
     */
    private function tranOpenId()
    {
        $members = \app\common\model\Member::select();
        foreach ($members as $member) {
            $member->official_openid = $member->union_id;
            $member->union_id = null;
            $member->save();
        }
        return 'success';
    }


    /**
     * transUnionId
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Apidoc\Title("转换unionid")
     */
    private function transUnionId()
    {
        $members = \app\common\model\Member::select();
        $config = [
            'app_id' => config('wechat_official_account.app_id'),
            'secret' => config('wechat_official_account.secret'),
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);

        foreach ($members as $member) {
            if ($member->official_openid) {
                $user = $app->user->get($member->official_openid);
                $member->union_id = $user['unionid'];
                $member->save();
            }
        }
        return 'success';
    }


    /**
     * getLastOrder
     * @Apidoc\Title("获取最后的订单错误")
     */
    public function getLastOrder()
    {
        dump(cache('order'));
    }

    public function title()
    {
        $keywords = input('keywords', '汽车销售', 'trim');
        ChatGpt::chat('给出 40 个关于`' . $keywords . '`的seo标题', true, 'test1', true);
//        ChatGpt::chat('写一篇关于`'.$keywords.'`的文章,不少于1000字', true, 'test1', false);
    }

    /**
     * index
     * @Apidoc\Title("test")
     */
    private function index()
    {
        header('X-Accel-Buffering: no');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        set_time_limit(0); //防止超时
        ob_end_clean();
        ob_implicit_flush(1);

        $res = ChatGpt::chat('给出 40 个关于`火腿肠`的seo标题,结果列表不要任何符号', true);
        $body = $res->getBody();
        $arr = [];
        $last_data = '######';
        $titles = [];
        $one_line = '';

        while (!$body->eof()) {
            $arr[] = $body->read(800);

            $length = sizeof($arr);

            $words = explode("\n\n", $arr[$length - 1]);
            $words_length = sizeof($words);
            foreach ($words as $word_index => $word) {
                $full_data = json_decode(str_replace('data: ', '', $word), true);

                $finish_reason = null;
                $this_str = '####';
                if ($full_data) {
                    $finish_reason = $full_data['choices'][0]['finish_reason'];
                    if (!$finish_reason) {
                        $word_arr[] = $full_data;
                        $this_str = $full_data['choices'][0]['delta']['content'];
                    }


                } else {
                    if ($word_index != 0) {
                        $last_data = $word;
                    } else {

                        $full_data = json_decode(str_replace('data: ', '', $last_data . $word), true);
                        $finish_reason = $full_data['choices'][0]['finish_reason'];
                        if (!$finish_reason) {
                            $word_arr[] = $full_data;

                            $this_str = $full_data['choices'][0]['delta']['content'];
                        }

                        $last_data = '######';
                    }
                }

                if ($this_str !== '####') {
                    $one_line .= $this_str;


                    if (strpos($this_str, "\n") !== false) {
                        if (trim($one_line) !== '') {
                            $titles[] = trim($one_line);

                            $c = "event:test1" . PHP_EOL; //定义事件
                            $c .= "data:" . $titles[sizeOf($titles) - 1] . PHP_EOL; //推送内容
                            echo $c . PHP_EOL;


                        }
                        $one_line = '';
                    }


                } else {
                    if ($finish_reason) {
                        $titles[] = trim($one_line);

                        $c = "event:test1" . PHP_EOL; //定义事件
                        $c .= "data:" . $titles[sizeOf($titles) - 1] . PHP_EOL; //推送内容
                        echo $c . PHP_EOL;

                        $one_line = '';
                    }
                }

            }

        }


//        dump($titles);


        $c = "event:test1" . PHP_EOL; //定义事件
        $c .= "data:end" . PHP_EOL; //推送内容
        echo $c . PHP_EOL;
    }


    /**
     * NotHeaders
     * getToken
     * @return \think\response\Json
     *
     * @Apidoc\Title("getToken")
     *
     */
    public function getToken()
    {
        $token = JWTAuth::builder(['uid' => 1]);
        return success('ok', 'Bearer ' . $token);
    }

    public function sse()
    {
        return View::fetch();
    }

    /**
     * forceUpdateTokenTime
     * @Apidoc\Title("强制更新token测试")
     */
    private function forceUpdateTokenTime()
    {
        $model = GptToken::order('update_time', 'asc')->where('id', '>', 1)->find();
        $model->force()->save();
        $data = GptToken::order('update_time', 'asc')->select();
        dump($data->toArray());
    }


    /**
     * cron
     * @Apidoc\Title("查看当前定时任务")
     */
    public function cron()
    {
        $res = Crontab::getJobs();
        dump($res);


    }


    private function cronAdd()
    {
        $job = '* * * * * curl https://member.ai-dog.net/api/cron/createArticlesPerMember';
        $job1 = '* * * * * curl https://member.ai-dog.net/api/cron/createArticlesOld';
        $job2 = '0 0 * * * curl https://member.ai-dog.net/api/cron/todayToYesterday';

        Crontab::addJob($job);
        Crontab::addJob($job1);
        Crontab::addJob($job2);
        return 'success';
    }


    private function cronDelete()
    {
        $res = Crontab::getJobs();
        foreach ($res as $item) {
            Crontab::removeJob($item);
        }
        return 'success';
    }


    public function order()
    {
        dump(cache('order')->toArray());
    }

    /**
     * @Apidoc\Method("post")
     * @Apidoc\Title("getPwd")
     * @Apidoc\Param("pwd")
     * getPwd
     * @return string
     */
    public function getPwd()
    {
        $pwd = input('pwd');
        return md5($pwd . '_spencer_salt');
    }


    /**
     * testImg
     * @Apidoc\Method("post")
     * @Apidoc\Title("testImg")
     */
    private function testImg()
    {
        $url = 'https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/VqcgbxnNJonPtexVi6dcWLzannz/?fallback_source=0&amp;height=1280&amp;mount_node_token=C6yGds0iQoWa8axoNuGcLBdfnId&amp;mount_point=docx_image&amp;policy=equal&amp;width=1280';
        echo <<<EOF
 <a href="{$url}">$url</a>
EOF;


        try {

            $referer = 'https://dabfzzc920q.feishu.cn';

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Referer: $referer\r\n"
                )
            ));

            $content = file_get_contents($url, false, $context);
            dump($content);
        } catch (\Exception $e) {
            dump($e);
        }
    }


    /**
     * import
     * @Apidoc\Title("导入咒语")
     *
     */
    private function import()
    {
        set_time_limit(0);
        $content = file_get_contents('./file.json');
        $arr = json_decode($content, true);
        $all = [];
        $cats = [];
        foreach ($arr as $item) {
            if (!$cats[$item['Category']]) {
                $cat = \app\common\model\ChatPromptClassification::create([
                    'name' => $item['Category'],
                    'colour' => sprintf("#%06x", rand(0, 0xFFFFFF)),
                ]);
                $cats[$item['Category']] = $cat->id;
            }
        }
        foreach ($arr as $item) {
            $all[] = [
                'name' => $item['Title'],
                'title' => $item['PromptHint'],
                'chat_prompt_front' => $item['Teaser'],
                'chat_prompt' => str_replace('TARGETLANGUAGE', '中文', $item['Prompt']),
                'chat_prompt_classification_id' => $cats[$item['Category']]
            ];

        }
        $chatPrompt = new \app\common\model\ChatPrompt();
        $chatPrompt->saveAll($all);
        return 'success';
    }


    /**
     * chat2
     * @Apidoc\Title("chat2Test")
     */
    private function chat2()
    {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no');
        Chat2::test();

    }

    /**
     * addMemberRef
     * @Apidoc\Title("增加member的ref")
     */
    private function addMemberRef()
    {
        $members = \app\common\model\Member::select();
        foreach ($members as $member) {
            $member->ref = substr(sha1($member->id), -8);
            $member->save();
        }
        echo 'success';

    }


    private function getCronJob($plan): string
    {
        $job = config('wechat.base_url') . '/api/cron/doPlan?id=';
        //  每天
        if ($plan['period'] == 1) {
            $plan['day'] = '*';
            $plan['month'] = '*';
            $plan['week'] = '*';
        }
        // 每周
        if ($plan['period'] == 2) {
            $plan['month'] = '*';
            $plan['day'] = '*';
        }
        // 每月
        if ($plan['period'] == 3) {
            $plan['week'] = '*';
            $plan['month'] = '*';
        }
        $time = $plan['minute'] . ' ' . $plan['hour'] . ' ' . $plan['day'] . ' ' . $plan['month'] . ' ' . $plan['week'] . ' ';
        return $time . 'curl ' . $job . $plan['id'];
    }


    /**
     * refreshCron
     * @Apidoc\Title("用于数据转移后的更新定时任务")
     */
    public function refreshCron()
    {
        $url = config('wechat.base_url');
        $job = "* * * * * curl {$url}/api/cron/createArticlesPerMember";
        $job1 = "* * * * * curl {$url}/api/cron/createArticlesOld";
        $job2 = "0 0 * * * curl {$url}/api/cron/todayToYesterday";
        $job3 = "* * * * * curl {$url}/api/Cron/doArticleTitleTask";
        $job4 = "* * * * * curl {$url}/api/cron/renewApiKey";

        Crontab::removeJob($job);
        Crontab::removeJob($job1);
        Crontab::removeJob($job2);
        Crontab::removeJob($job3);
        Crontab::removeJob($job4);

        Crontab::addJob($job);
        Crontab::addJob($job1);
        Crontab::addJob($job2);
        Crontab::addJob($job3);
        Crontab::addJob($job4);


        $plans = PushPlan::select();
        foreach ($plans as $plan) {
            $cron = $this->getCronJob($plan->getData());
            Crontab::removeJob($cron);

            // 添加新的任务
            if ($plan['is_open']) {
                $cron = $this->getCronJob($plan->getData());
                Crontab::addJob($cron);
            }
        }
        return 'success';

    }


    /**
     * @Apidoc\Title("配置公众号菜单")
     * configOfficialMenu
     */
    public function configOfficialMenu()
    {
        $menu = [
            [
                "type" => "miniprogram",
                "name" => "文案生成",
                "url" => "https://www.ai-dog.net",
                "appid" => config('front_end.app_id'),
                "pagepath" => "pages/home/home"
            ],
            [
                "type" => "miniprogram",
                "name" => "ChatDOG",
                "url" => "https://www.ai-dog.net",
                "appid" => config('front_end.app_id'),
                "pagepath" => "pages/chatDoG/chatDoG"
            ],
            [
                "type" => "miniprogram",
                "name" => "文章生成",
                "url" => "https://www.ai-dog.net",
                "appid" => config('front_end.app_id'),
                "pagepath" => "pages/titleGeneration/titleGeneration"
            ],
        ];
        $config = config('wechat_official_account');
        $wechat = Factory::officialAccount($config);
        $wechat->menu->delete();
        $wechat->menu->create($menu);

        return 'success';

    }


}
